<template>
  <div class=" wh-100" style="background-color:#fff;" v-loading="loading">
    <!--title&添加场地-->
    <div class="d-flex-between-center px-12 " style="height: 60px;border-bottom: 1px solid #eef1f7">
      <div class="fs-16 fw-7">校区管理</div>
      <Button type="primary" @click="addSite">+添加校区</Button>
    </div>
    <!--搜索&导出-->
    <div class="d-flex-between-center px-12" style="height: 60px;border-bottom: 1px solid #eef1f7">
        <div class="d-flex">
            <Button @click="exportData">导出数据</Button>
            <Button type="dashed" @click="changeTip">{{ openTip ? '关闭提示' : '开启提示' }}</Button>
        </div>
        <div class="d-flex align-items-center">
        <Input size="small" class="d-flex-center" @keydown.native.enter.prevent="toSearch" @on-keyup="pageParams.campusName=pageParams.campusName.replace(/\s/g,'')" v-model="pageParams.campusName" placeholder="按校区名称查找"></Input>
        <Button type="primary" size="small" style="width: 80px;border-radius: 0  3px 3px  0"
          class="ml-0 vertical-align-bottom " @click="toSearch">搜索
        </Button>
      </div>
    </div>
    <!--表格-->
    <div v-ref-height="abca" style="height: calc(100% - 190px)">
        <Alert v-show="openTip" show-icon>
            已选择
            <span >{{ selectList.length }}</span>
            项
            <a @click="toggleSelection">清空</a>
        </Alert>
      <Table :height="abca.value - heightNmber" ref="selection"  :columns="tableColumns" :data="tableData" @on-selection-change="onSelectionChange">
        <template slot-scope="{row}" slot="currentStatus">
          <span v-if="row.currentStatus == 'true'" style="color: green">可用</span>
          <span v-if="row.currentStatus == 'false'" style="color: red">不可用</span>
        </template>
        <template slot-scope="{row}" slot="operate">
          <span class="table-btn mr-12" @click="openUpdateDialog(row)">修改</span>
          <span class="table-btn" @click="deleteData(row.id)">删除</span>
        </template>
      </Table>
      <div class="w-100  fs-14 d-flex-center" style="height:55px;background-color:#fff;">
        <Page show-total :total="pagetotal" :page-size="pageParams.pageSize" :current="pageParams.pageNumber" @on-change="changePage"
          @on-page-size-change="changePageSize" show-elevator show-sizer class-name="d-flex-center" size="small" />
      </div>
    </div>
    <!--修改弹框-->
    <el-dialog title="修改校区信息" :visible.sync="dialogFormVisible">
      <Form :label-width="90" class="mt-20" ref="updateRef" :model="updateForm" :rules="updateFormRules">
        <FormItem style="width: 400px" label="校区名称" prop="campusName">
          <Input v-model="updateForm.campusName" placeholder="输入校区名称"></Input>
        </FormItem>
        <FormItem label="是否启用" prop="currentStatus">
          <el-switch v-model="updateForm.currentStatus" />
        </FormItem>
        <FormItem style="width: 400px" label="详细地址" prop="campusAddress">
          <Input v-model="updateForm.campusAddress" placeholder="填写详细校区详细地址"></Input>
        </FormItem>
      </Form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addCampusAPI,
  deleteCampusAPI, exportDataAPI,
  getAllCampusAPI,
  updateCampusAPI
} from "../../../api/bys/siteAdministration/index"
// region TODO 表格
const tableColumns = [
  {
    type: 'selection',
    width: 60,
    key: 'name'
  },
  {
    title: '校区名称',
    key: 'campusName'
  },
  {
    title: '详细位置',
    key: 'campusAddress'

  },
  {
    title: '当前状态',
    slot: 'currentStatus',
  },
  {
    title: '更新时间',
    key: 'createTime'
  },
  {
    title: '操作',
    slot: 'operate'
  },
]
const tableData = []
// endregion
// region TODO 表单
const updateForm = {
  campusName: '',
  currentStatus: '',
  campusAddress: ''
}
const updateFormRules = {
  campusName: [{ required: true, message: '必填项', trigger: 'blur' }],
  campusAddress: [{ required: true, message: '必填项', trigger: 'blur' }],
}
// region TODO 分页
const pages = {
  pageSize: 10,
  pageIndex: 1,
  total: 0
}
// endregion
export default {
  data() {
    return {
      selectIds: [],
      dialogFormVisible: false,
      pagetotal: '',
      updateForm,
      updateFormRules,
      loading: false,
      pages,
      tableColumns,
      tableData,
      abca: {
        value: 0
      },
      form: {},
      pageParams: {
        campusName: '',
        pageNumber: 1,
        pageSize: 10,
        sort: '',
        order: ''

      },
        heightNmber:20,
        openTip:true,
        selectList:[],
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
      changeTip(){
          this.openTip = !this.openTip
          if(this.openTip){
              this.heightNmber=20
          }else{
              this.heightNmber=0
          }
      },
      toggleSelection() {
          this.$refs.selection.selectAll(false);
      },
    toSearch() {
      console.log(this.pageParams.campusName)
      this.getList()
    },
    addSite() {
      this.$router.push({
        name: 'AddCampus'
      })
    },
    getList() {
      this.loading = true
      getAllCampusAPI(this.pageParams).then((res) => {
        if (res.success) {
          this.loading = false
          console.log("校区管理", res)
          this.tableData = res?.result?.records || []
          this.pagetotal = res?.result?.total || 0
        } else {
          this.loading = false
          this.tableData = []
          this.pagetotal = 0
        }

      }).catch(err => {
        console.log(err)
        this.loading = false
      })
    },
    // region TODO 打开修改弹窗
    openUpdateDialog(row) {
      this.updateForm = JSON.parse(JSON.stringify(row))
      this.updateForm.currentStatus = JSON.parse(this.updateForm.currentStatus);
      console.log(this.updateForm, '修改')
      console.log(row, 'row')
      this.dialogFormVisible = true
    },
    // endregion
    // region TODO 选择数据变化
    onSelectionChange(value) {
      this.selectList=value
      this.selectIds = value
    },
    // endregion
    // region TODO 删除一条数据
    deleteData(id) {
      this.$confirm('您确定删除该校区信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCampusAPI({
          id: id
        }).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    // endregion
    // region TODO 修改一条数据
    updateData() {
      this.$refs.updateRef.validate((valid) => {
        if (valid) {
          this.$confirm('你确定修改该信息吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.loading = true
            updateCampusAPI(this.updateForm).then((res) => {
              if (res.success) {
                this.$message.success(res.message);
                this.dialogFormVisible = false
                this.getList()
                this.updateForm = ''
                this.loading = false
              } else {
                this.$message.error(res.message);
                this.loading = false

              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消修改'
            });
            this.updateForm = ''
          });
        } else {
          this.$message.error('请完善相关信息！')
          return false;
        }

      })

    },
    // endregion
    // region TODO 导出数据
    exportData() {
      let selectDatas = []
      for (let i = 0; i < this.selectIds.length; i++) {
        console.log("itemID2", this.selectIds[i].id)
        selectDatas.push(this.selectIds[i].id)
      }
      console.log("导出id", selectDatas)

      exportDataAPI(selectDatas)
        .then(res => {
          const blob = new Blob([res]);
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', '校区管理.xlsx');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

        })
        .catch(error => {
          console.error('Error during export:', error);
        });


    },
    // endregion
    // region TODO 分页
    changePage(val) {
      this.pages.pageNumber = val
      //调接口
      this.getList()

    },
    changePageSize(val) {
      this.pages.pageSize = val;
      //调接口
      this.getList()
    },
    // endregion
  }

}
</script>

<style scoped>
.table-btn {
  color: #1677FF;
  cursor: pointer;
}
</style>
